package com.my.javaweb;

import com.my.frame.pojo.User;
import com.my.frame.service.IUserService;
import com.my.frame.service.impl.UserServiceImpl;
import com.my.frame.service.impl.UserServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "LoginDemo" ,urlPatterns = "/login")
public class LoginDemo extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取请求数据
        String name = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        //处理请求
        IUserService userService = new UserServiceImpl();
        User user = userService.login(name,pwd);
        if(user != null){
            Cookie c = new Cookie("uid",user.getId()+"");
            c.setMaxAge(3*24*3600);//三天免密
            c.setPath("/Servlet");
            resp.addCookie(c);//响应到浏览器
            //将数据存储到session对象中
            HttpSession hs = req.getSession();//获取session
            hs.setAttribute("user",user);
            //记录登陆网站次数
            ServletContext sc = this.getServletContext();
//            int counts = (int)sc.getAttribute("counts");//第一次回出现空指针异常
            if(sc.getAttribute("counts")!=null){
                int counts = (int)sc.getAttribute("counts");
                counts+=1;//自增
                sc.setAttribute("counts",counts);//存储
            }else
                sc.setAttribute("counts",1);
            //重定向去菜单
            System.out.println("登陆成功");
            resp.sendRedirect("/Servlet/Menu.html");
            return;
        }
        else {
            System.out.println("登陆失败");
            //重定向
            resp.sendRedirect("/Servlet/MyTown.html");
            return;
        }
    }
}
